package com.cby.operation.pay.ui

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import com.cby.operation.common.ext.getDrawableId
import com.cby.operation.common.ext.getId
import com.cby.operation.common.ext.getLayoutId
import com.cby.operation.pay.bean.PayChannel
import java.util.*

/**
 * Description:PayChannelsAdapter
 *
 * @author 陈宝阳
 * @create 2020/8/7 10:18
 */
class PayChannelsAdapter(private val context: Context, channels: List<PayChannel>?) :
    BaseAdapter() {

    private val payChannels: MutableList<PayChannel> = ArrayList()

    /**
     * 选中的选项
     */
    var selectPayChannel: PayChannel? = null
        private set

    override fun getCount(): Int {
        return payChannels.size
    }

    override fun getItem(position: Int): PayChannel {
        return payChannels[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val viewHolder: ViewHolder
        var itemView: View? = convertView
        //判断是否有缓存
        if (itemView == null) {
            itemView = LayoutInflater.from(context)
                .inflate(context.getLayoutId("pay_item_channel"), null)
            viewHolder = ViewHolder(itemView)
            itemView.tag = viewHolder
        } else {
            //得到缓存的布局
            viewHolder = itemView.tag as ViewHolder
        }

        //设置图标
        viewHolder.payChannelIconIv.setImageResource(
            context.getDrawableId(payChannels[position].payChannelIcon)
        )
        //设置名称
        viewHolder.payChannelNameTv.text = payChannels[position].payChannelName
        //设置选择项
        viewHolder.payChannelChoiceCb.isChecked = payChannels[position].select
        viewHolder.payChannelChoiceCb.isClickable = false
        //设置选择事件
        itemView!!.setOnClickListener {
            choicePayChannel(position)
            selectPayChannel = payChannels[position]
        }
        return itemView
    }

    private fun choicePayChannel(position: Int) {
        for (i in payChannels.indices) {
            payChannels[i].select = position == i
        }
        notifyDataSetChanged()
    }

    /**
     * ViewHolder类
     */
    private inner class ViewHolder internal constructor(view: View) {

        var payChannelIconIv: ImageView = view.findViewById(context.getId("iv_pay_channel_icon"))
        var payChannelNameTv: TextView = view.findViewById(context.getId( "tv_pay_channel_name"))
        var payChannelChoiceCb: CheckBox = view.findViewById(context.getId( "cb_pay_channel_choice"))

    }

    init {
        payChannels.addAll(channels!!)
        if (payChannels.size > 0) {
            selectPayChannel = payChannels[0]
        }
    }
}